<?php
/**
 * 编辑考试项目页面
 * 功能：编辑现有考试项目信息
 * 权限：仅考试项目管理员可访问
 */

session_start();

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
require_once 'database.php';

// 包含统一导航栏
if (file_exists('common/navigation.php')) {
    require_once 'common/navigation.php';
}

// 权限验证函数
if (!function_exists('getUserRoles')) {
    function getUserRoles($user_id, $conn) {
        $roles = [];
        try {
            $sql = "SELECT role FROM user_roles WHERE user_id = ?";
            $stmt = $conn->prepare($sql);

            if ($stmt) {
                $stmt->bind_param("s", $user_id);
                $stmt->execute();
                $result = $stmt->get_result();

                while ($row = $result->fetch_assoc()) {
                    $roles[] = $row['role'];
                }
                $stmt->close();
            }
        } catch (Exception $e) {
            error_log("获取用户角色失败: " . $e->getMessage());
        }

        return $roles;
    }
}

// 权限验证
$user_roles = getUserRoles($current_user_id, $conn);
if (!in_array('考试项目管理员', $user_roles)) {
    $_SESSION['error_message'] = "访问被拒绝：您需要考试项目管理员权限才能访问此页面";
    header('Location: access_denied.php');
    exit();
}

// 获取项目ID
$exam_id = intval($_GET['id'] ?? 0);
if ($exam_id <= 0) {
    $_SESSION['error_message'] = "无效的项目ID";
    header('Location: exam_projects.php');
    exit();
}

$project = null;
$error_message = '';
$success_message = '';

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $exam_name = trim($_POST['exam_name'] ?? '');
        $exam_date = $_POST['exam_date'] ?? '';
        $end_date = $_POST['end_date'] ?? '';
        $subject_count = intval($_POST['subject_count'] ?? 0);
        $students_per_subject = intval($_POST['students_per_subject'] ?? 0);
        $rooms_per_subject = intval($_POST['rooms_per_subject'] ?? 0);
        $invigilators_per_subject = intval($_POST['invigilators_per_subject'] ?? 0);

        // 验证必填字段
        if (empty($exam_name)) {
            throw new Exception("考试名称不能为空");
        }
        if (empty($exam_date)) {
            throw new Exception("考试日期不能为空");
        }
        if ($subject_count <= 0) {
            throw new Exception("科目数量必须大于0");
        }
        if ($students_per_subject <= 0) {
            throw new Exception("每科学生数必须大于0");
        }

        // 更新项目信息
        $update_sql = "UPDATE exams SET 
                       exam_name = ?, 
                       exam_date = ?, 
                       end_date = ?, 
                       subject_count = ?, 
                       students_per_subject = ?, 
                       rooms_per_subject = ?, 
                       invigilators_per_subject = ?,
                       updated_at = NOW()
                       WHERE id = ?";

        $stmt = $conn->prepare($update_sql);
        if (!$stmt) {
            throw new Exception("数据库准备失败: " . $conn->error);
        }

        $stmt->bind_param("sssiiii",
            $exam_name,
            $exam_date,
            $end_date,
            $subject_count,
            $students_per_subject,
            $rooms_per_subject,
            $invigilators_per_subject,
            $exam_id
        );

        if ($stmt->execute()) {
            $_SESSION['success_message'] = "项目「{$exam_name}」更新成功";
            header('Location: exam_projects.php');
            exit();
        } else {
            throw new Exception("更新失败: " . $stmt->error);
        }

    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// 获取项目信息
try {
    $sql = "SELECT * FROM exams WHERE id = ? AND status = 'active'";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        throw new Exception("数据库查询准备失败");
    }

    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        $_SESSION['error_message'] = "项目不存在或已被删除";
        header('Location: exam_projects.php');
        exit();
    }

    $project = $result->fetch_assoc();
    $stmt->close();

} catch (Exception $e) {
    $_SESSION['error_message'] = "获取项目信息失败: " . $e->getMessage();
    header('Location: exam_projects.php');
    exit();
}

$page_title = '编辑考试项目 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <style>
        .main-content {
            margin-top: 20px;
            padding-bottom: 40px;
        }

        .page-header {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        .form-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 30px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h5 {
            color: #495057;
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .btn-group-custom {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 30px;
        }

        @media (max-width: 768px) {
            .btn-group-custom {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
<!-- 统一导航栏 -->
<?php
if (file_exists('common/navigation.php')) {
    include_once 'common/navigation.php';
} else {
    echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="user_home.php">考务管理系统</a>
                    <div class="navbar-nav ms-auto">
                        <span class="navbar-text me-3">用户: ' . htmlspecialchars($current_user_id) . '</span>
                        <a class="nav-link" href="logout.php">退出登录</a>
                    </div>
                </div>
              </nav>';
}
?>

<!-- 主要内容 -->
<div class="container main-content">
    <!-- 页面标题 -->
    <div class="page-header">
        <h1 class="mb-2">
            <i class="fas fa-edit"></i> 编辑考试项目
        </h1>
        <p class="mb-0">修改项目「<?php echo htmlspecialchars($project['exam_name']); ?>」的基本信息</p>
    </div>

    <!-- 错误消息 -->
    <?php if (!empty($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- 编辑表单 -->
    <div class="form-container">
        <form method="POST" action="">
            <!-- 基本信息 -->
            <div class="form-section">
                <h5><i class="fas fa-info-circle"></i> 基本信息</h5>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="exam_name" class="form-label">考试名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="exam_name" name="exam_name"
                               value="<?php echo htmlspecialchars($project['exam_name']); ?>" required>
                    </div>

                    <div class="col-md-3 mb-3">
                        <label for="exam_date" class="form-label">考试开始日期 <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" id="exam_date" name="exam_date"
                               value="<?php echo $project['exam_date']; ?>" required>
                    </div>

                    <div class="col-md-3 mb-3">
                        <label for="end_date" class="form-label">考试结束日期</label>
                        <input type="date" class="form-control" id="end_date" name="end_date"
                               value="<?php echo $project['end_date']; ?>">
                    </div>
                </div>
            </div>

            <!-- 考试规模 -->
            <div class="form-section">
                <h5><i class="fas fa-chart-bar"></i> 考试规模</h5>

                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label for="subject_count" class="form-label">科目数量 <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="subject_count" name="subject_count"
                               value="<?php echo $project['subject_count']; ?>" min="1" required>
                    </div>

                    <div class="col-md-3 mb-3">
                        <label for="students_per_subject" class="form-label">每科学生数 <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="students_per_subject" name="students_per_subject"
                               value="<?php echo $project['students_per_subject']; ?>" min="1" required>
                    </div>

                    <div class="col-md-3 mb-3">
                        <label for="rooms_per_subject" class="form-label">每科课室数</label>
                        <input type="number" class="form-control" id="rooms_per_subject" name="rooms_per_subject"
                               value="<?php echo $project['rooms_per_subject']; ?>" min="0">
                    </div>

                    <div class="col-md-3 mb-3">
                        <label for="invigilators_per_subject" class="form-label">每科监考员数</label>
                        <input type="number" class="form-control" id="invigilators_per_subject" name="invigilators_per_subject"
                               value="<?php echo $project['invigilators_per_subject']; ?>" min="0">
                    </div>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="btn-group-custom">
                <a href="exam_projects.php" class="btn btn-secondary btn-lg">
                    <i class="fas fa-arrow-left"></i> 返回列表
                </a>
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="fas fa-save"></i> 保存修改
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 表单验证
    document.querySelector('form').addEventListener('submit', function(e) {
        const examName = document.getElementById('exam_name').value.trim();
        const examDate = document.getElementById('exam_date').value;
        const subjectCount = parseInt(document.getElementById('subject_count').value);
        const studentsPerSubject = parseInt(document.getElementById('students_per_subject').value);

        if (!examName) {
            alert('请输入考试名称');
            e.preventDefault();
            return;
        }

        if (!examDate) {
            alert('请选择考试日期');
            e.preventDefault();
            return;
        }

        if (subjectCount <= 0) {
            alert('科目数量必须大于0');
            e.preventDefault();
            return;
        }

        if (studentsPerSubject <= 0) {
            alert('每科学生数必须大于0');
            e.preventDefault();
            return;
        }
    });
</script>

<?php
// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>
</body>
</html>